package com.innovation.ic.b1b.framework.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

/**
 * 邮件工具类
 */
public class MailUtil {

    public static void sendEMail(String mailHost, String mailTransportProtocol, String mailSmtpAuth, String socketFactoryClass,
                                 String socketFactoryFallback, Integer port, String mailUsername, String mailPassword,
                                 String mailSubject, String mailContent, String toUsername) {

        Properties properties = new Properties();
        properties.put("mail.smtp.host", mailHost);
        properties.put("mail.transport.protocol", mailTransportProtocol);
        properties.put("mail.smtp.auth", mailSmtpAuth);
        properties.put("mail.smtp.socketFactory.class", socketFactoryClass); // 使用JSSE的SSL
        properties.put("mail.smtp.socketFactory.fallback", socketFactoryFallback); // 只处理SSL的连接,对于非SSL的连接不做处理
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.socketFactory.port", port);

        Session session = Session.getInstance(properties);
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        Transport transport = null;

        try {
            // 发件人
            Address fromAddress = new InternetAddress(mailUsername);
            message.setFrom(fromAddress);
            // 收件人
            Address toAddress = new InternetAddress(toUsername);
            message.setRecipient(MimeMessage.RecipientType.TO, toAddress); // 设置收件人,并设置其接收类型为TO

            // 主题message.setSubject(changeEncode(emailInfo.getSubject()));
            message.setSubject(mailSubject);
            // 时间
            message.setSentDate(new Date());

            Multipart multipart = new MimeMultipart();

            // 创建一个包含HTML内容的MimeBodyPart
            BodyPart html = new MimeBodyPart();
            // 设置HTML内容
            html.setContent(mailContent, "text/html; charset=utf-8");
            multipart.addBodyPart(html);
            // 将MiniMultipart对象设置为邮件内容
            message.setContent(multipart);
            message.saveChanges();
            transport = session.getTransport("smtp");
            transport.connect(mailHost, mailUsername, mailPassword);
            transport.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
